package com.bfmet.common.base;

import java.util.List;
import java.util.Map.Entry;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

import com.bfmet.common.DAOService;
import com.bfmet.common.Parameter;

public class DAOWrapper extends GenericMBean {

	public <T> T getOneResult(Class<T> clazz, Object id) {
		EntityManager em = DAOService.getEM();
		try {
			return em.find(clazz, id);
		} finally {
			em.close();
		}
	}

	public <T> List<T> query(Class<T> clazz, int resultSize,
			Parameter... parameters) {
		EntityManager em = DAOService.getEM();
		try {
			StringBuilder where = new StringBuilder();
			if (parameters != null && parameters.length > 0) {
				where.append("where ");
				for (Entry<String, Object> entry : parameters) {
					where.append("n." + entry.getKey() + "=:" + entry.getKey()
							+ " ");
				}
			}

			TypedQuery<T> query = em.createQuery(
					"select n from " + clazz.getSimpleName() + " n "
							+ where.toString() + " order by n.id desc", clazz);
			if (parameters != null && parameters.length > 0) {
				for (Entry<String, Object> entry : parameters) {
					query.setParameter(entry.getKey(), entry.getValue());
				}
			}
			query.setMaxResults(resultSize);
			return query.getResultList();
		} finally {
			em.close();
		}
	}

	public <T> List<T> query(Class<T> clazz, String jpasql, int resultSize) {
		EntityManager em = DAOService.getEM();
		try {
			TypedQuery<T> query = em.createQuery(jpasql, clazz);
			query.setMaxResults(resultSize);
			return query.getResultList();
		} finally {
			em.close();
		}
	}
}
